package com.db.jdbc;

import com.bean.Admin;
import com.bean.PaginationSupport;
import com.db.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhi keyan
 * @create 2020-12-12 15:30
 */
@Repository
public class JdbcAdminRepository implements AdminRepository {

    private JdbcTemplate jdbc;

    private static final String SELECT_ADMIN = "select adminID, adminName, password, isDelete from admin ";

    private static final String SELECT_PAGE_ADMIN = SELECT_ADMIN +"where isDelete = false order by adminID desc limit ? offset ? ";

    private static final String INSERT_ADMIN = "insert into admin (adminID, adminName, password, isDelete) values (?,?,?,?) ";

    private static final String MAX_ID = "select max(adminID) from admin ";

    private static final String DELETE_ADMIN = "update admin set isDelete = ? where adminID = ? ";

    @Autowired
    public JdbcAdminRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    private static class AdminRowMapper implements RowMapper<Admin> {
        public Admin mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Admin(rs.getInt("adminID"), rs.getString("adminName")
            ,rs.getString("password"), rs.getBoolean("isDelete"));
        }
    }

    @Override
    public Admin save(Admin admin) {
        int adminID = insertAdminandReturnID(admin);
        return new Admin(adminID,admin.getAdminName(),admin.getPassword(),false);
        //jdbc.update(INSERT_ADMIN, admin.getAdminID(), admin.getAdminName(), admin.getPassword(), admin.getIsDelete());
        //return admin;
    }

    private int insertAdminandReturnID(Admin admin){
        SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbc).withTableName("admin");
        jdbcInsert.setGeneratedKeyName("adminID");
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("adminName", admin.getAdminName());
        args.put("password", admin.getPassword());
        args.put("isDelete", false);
        int adminID = jdbcInsert.executeAndReturnKey(args).intValue();
        return adminID;
    }

    @Override
    public Admin findByAdminID(int adminID) {
        Admin admin = null;
        try{
            admin = jdbc.queryForObject(SELECT_ADMIN + " where adminID=?", new AdminRowMapper(), adminID);
        }catch (Exception e){

        }
        return admin;
    }

    @Override
    public Admin findByAdminName(String username) {
       Admin admin = null;
       try{
           admin = jdbc.queryForObject(SELECT_ADMIN + " where adminName=? " , new AdminRowMapper(), username);
       }catch(Exception e){
       }
       return admin;
    }

    @Override
    public Admin findByAdminName(String username, String password) {
        Admin admin = null;
        try{
            admin = jdbc.queryForObject(SELECT_ADMIN + " where adminName=? and password=?", new AdminRowMapper(), username, password);
        }catch(Exception e){

        }
        return admin;
    }

    @Override
    public long countAdmin() {
        return jdbc.queryForLong("select count(adminID) from admin ");
    }

    @Override
    public long countExistAdmin() {
        return jdbc.queryForLong("select count(adminID) from admin where isDelete = ?", "false");
    }

    @Override
    public PaginationSupport<Admin> findAdminPage(int pageNo, int pageSize) {
        int totalCount = (int) countAdmin();
        int startIndex = PaginationSupport.convertFromPageToStartIndex(pageNo, pageSize);
        if (totalCount < 1)
            return new PaginationSupport<Admin>(new ArrayList<Admin>(0), 0);

        List<Admin> items = jdbc.query(SELECT_PAGE_ADMIN , new AdminRowMapper(), pageSize, startIndex);
        PaginationSupport<Admin> ps = new PaginationSupport<Admin>(items, totalCount, pageSize, startIndex);
        return ps;
    }

    @Override
    public void deleteAdmin(Admin deleteAdmin) {
        //TODO
        try{
            String status ="true";
            jdbc.update("update admin set isDelete = ? where adminID = ? " , status , deleteAdmin.getAdminID());
        }catch (Exception e){

        }
    }


    @Override
    public Admin adminModify(Admin admin, String newAdminName, String newPassword) {
        try{
            jdbc.update("update admin set adminName = ?, password = ? where adminID = ? ", newAdminName, newPassword, admin.getAdminID());
            admin.setAdminName(newAdminName);
            admin.setPassword(newPassword);
        }catch (Exception e){
        }
        return admin;
    }

    @Override
    public int maxAdminID() {
        return jdbc.queryForInt(MAX_ID);
    }
}
